<template>
  <div class="user">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="userParams.query"
            @blur="search"
            clearable
            @clear="clear"
          >
            <template #append>
              <el-button
                icon="el-icon-search"
                @click="search(userParams)"
              ></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :sapn="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template v-slot="props">
            <el-switch
              v-model="props.row.mg_state"
              @change="userStatusChange(props.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 作用域插槽 -->
          <template v-slot="props">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delete props.row.id"
            ></el-button>
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialog(props.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalpage"
        :page-size="userParams.pagesize"
        :current-page="userParams.pagenum"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      v-model="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="修改用户" v-model="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="70px" @close="editDialogClose()">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser(editForm)">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱校验规则
    var checkMail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return callback();
      } else {
        callback(new Error("请输入正确的邮箱"));
      }
    };
    // 手机号校验规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      } else {
        callback(new Error("请输入正确的手机号"));
      }
    };
    return {
      userParams: {
        query: "",
        pagenum: 1,
        pagesize: 3,
      },
      userList: [],
      totalpage: null,
      addDialogVisible: false, // 控制添加用户表单是否显示
      editDialogVisible: false, // 控制编辑用户表单是否显示
      // 添加用户绑定表单
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加用户表单验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "密码长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkMail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 修改用户绑定表单
      editForm:{
        id:'',
        username:'',
        role_id:'',
        mobile:'',
        email:''
      },
      // 修改用户表单验证规则
      editRules:{
        email:[
          { required: true, message: "请输入邮箱", trigger:'blur'},
          { validator: checkMail, trigger: 'blur'}
        ],
        mobile:[
          { required: true, message: '请输入手机号', trigger: 'blur'},
          { validator: checkMobile, trigger:'blur'}
        ]
      }
    };
  },
  created() {
    // 获取用户数据
    console.log(this.userParams, 111);
    this.getUsers(this.userParams);
  },
  methods: {
    async getUsers(params) {
      console.log(params, 333);
      const res = await this.$axios.get("users", params);
      console.log(res, 222);
      if (res.data.meta.status !== 200) {
        return this.$message.error(res.data.meta.msg);
      } else {
        this.userList = res.data.data.users;
        this.totalpage = res.data.data.total;
      }
    },
    // pageSize改变时触发
    handleSizeChange(val) {
      this.userParams.pagesize = val;
      this.getUsers(this.userParams);
    },
    // currentPage改变时触发
    handleCurrentChange(val) {
      this.userParams.pagenum = val;
      this.getUsers(this.userParams);
    },
    async userStatusChange(userInfo) {
      const res = await this.$axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.data.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error("更新用户状态失败");
      } else {
        this.$message.success("更新用户状态成功");
      }
    },
    search() {
      this.getUsers(this.userParams);
    },
    clear() {
      this.getUsers(this.userParams);
    },
    addDialogClose() {
      // 对表单进行重置
      this.$refs.addForm.resetFields();
    },
    addUser() {
      // 对输入参数进行校验
      this.$refs.addForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) {
          return;
        } else {
          const res = await this.$axios.post("users", this.addForm);
          console.log(res, 333);
          if (res.data.meta.status !== 201) {
            this.$message.error("添加用户失败");
            this.addDialogVisible = false;
          } else {
            this.$message.success("添加用户成功");
            this.addDialogVisible = false;
            // 重新获取用户列表
            this.getUsers(this.userParams);
          }
        }
      });
    },
    // 编辑用户
    async editDialog(id) {
      this.editDialogVisible = true
      // 查询接口
      const {data: res} = await this.$axios.get(`users/${id}`)
      if(res.meta.status !== 200){
        return this.$message.error('查询用户信息失败')
      } else {
        this.editForm = res.data
      }
    },
    // 关闭修改对话框，清空当前数据
    editDialogClose(){
      this.$refs.editFormRef.resetFields()
    },
    editUser(params){
      // 对输入参数进行校验
      this.$refs.editFormRef.validate(async valid => {
        if(!valid){
          return
        } else {
          const {data: res} = await this.$axios.put(`users/${params.id}`,
          {
            email: params.email,
            mobile: params.mobile
          })
          if(res.meta.status !== 200){
            return this.$message.error('修改用户信息失败')
          } else {
            this.$message.success('修改用户信息成功')
            this.editDialogVisible = false
            // 重新获取用户信息列表
            this.getUsers(this.userParams)
          }
        }
      })
    }
  },
};
</script>

<style lang="less" scoped>
.el-col-24 {
  flex: 0 0 0;
}
.el-dialog__body {
  padding: 20px 20px !important;
  margin-right: 10px !important;
}
.el-form-item {
  margin-bottom: 20px;
}
.el-dialog_footer {
  padding: 0px 20px 20px;
}
</style>
